﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using YABE.Modules.Helpers;

namespace YABE.Controllers
{
	public class JsonController : Controller
	{
		private Models.IPostDL pd;

		public JsonController()
		{
            this.pd = new YABE.Models.PostDL();
		}

        public JsonController(Models.IPostDL pd)
        {
            this.pd = pd;
        }

		#region "actions"
		public JsonResult Titles()
		{
			List<YABE.Models.Post> posts = this.pd.GetPosts();

			List<object> list = new List<object>();

			foreach (YABE.Models.Post p in posts)
			{
				list.Add(new  { Value = p.PostID.ToString(), Text = p.Title });
			}

			return this.Json(list);
		}

		public JsonResult Posts()
		{
			List<YABE.Models.Post> posts = this.pd.GetPosts();

			return BuildPostJson(posts);
		}

		public JsonResult PostsYear(int year)
		{
			List<YABE.Models.Post> posts = this.pd.GetPosts(year);

			return BuildPostJson(posts);
		}

		public JsonResult PostsMonth(int year, int month)
		{
			List<YABE.Models.Post> posts = this.pd.GetPosts(year, month);

			return BuildPostJson(posts);
		}

		public JsonResult Months()
		{
			return this.Json(this.pd.GetPostMonths());
		}

		[Authorize]
		public JsonResult Delete(int id)
		{
			this.pd.DeletePost(id);

			return this.Json(id);
		}
		#endregion

		#region "private"
		private JsonResult BuildPostJson(List<YABE.Models.Post> posts)
		{
			List<YABE.Models.Json.Post> jsonPosts = new List<YABE.Models.Json.Post>();

			foreach (YABE.Models.Post p in posts)
			{
				jsonPosts.Add(new YABE.Models.Json.Post(p)
				{
					Url = string.Format("{0}/{1}/{2}/{3}/{4}", WebHelper.SiteRoot, p.Created.Year, p.Created.Month, p.Created.Day, Modules.Helpers.WebHelper.UrlifyTitle(p.Title)),
					EditUrl = string.Format("{0}/Posts/Edit/{1}", WebHelper.SiteRoot, p.PostID),
					DeleteUrl = string.Format("{0}/Json/Delete/{1}", WebHelper.SiteRoot, p.PostID) //Json/Delete/{0}
				});
			}

			return this.Json(jsonPosts);
		}
		#endregion
	}
}
